package me.flyray.crm.core.modules.netty.client;

import java.util.HashMap;
import java.util.Map;

import com.github.wxiaoqi.security.biz.common.util.MD5;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import net.sf.json.JSONObject;

public class Client {
	public static void main(String[] args) throws InterruptedException {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class);
//			b.option(ChannelOption.TCP_NODELAY, true);
			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel sc) throws Exception { 
					ChannelPipeline pipeline = sc.pipeline();
//					pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
					pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
			        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
			        pipeline.addLast(new ClientHandler());
				}
			});
			Channel channel = b.connect("127.0.0.1", 9090).sync().channel();
			Map<String, String> param = new HashMap<String, String>();
			String sign = MD5.md5("v-go-icloudpay");
		    param.put("lockId","v-go1");
		    param.put("sign", sign);
		    channel.writeAndFlush(JSONObject.fromObject(param).toString());
	        channel.closeFuture().sync();
	        Thread.sleep(2000);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}

}
